package services

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"snow-im/config"
	"sort"
	"time"

	"snow-im/app/models/ordermodel"
	"snow-im/app/utils/httpclient"
)

var (
	goods = []map[string]interface{}{
		map[string]interface{}{"goods_id": "buzhichun.bingingdou.com.week", "desc": "周会员", "expire": 7},
		map[string]interface{}{"goods_id": "buzhichun.bingingdou.com.month", "desc": "月会员", "expire": 30},
		map[string]interface{}{"goods_id": "buzhichun.bingingdou.com.quarter", "desc": "季度会员", "expire": 90},
		map[string]interface{}{"goods_id": "buzhichun.bingingdou.com.month.try", "desc": "前14天免费,之后季度会员", "expire": 104},
	}
)

func GetGoods() []map[string]interface{} {
	return goods
}
func GetPageOrders(page int64, pageSize int64, uuid string) (count int64, res []ordermodel.OrderDetail) {
	var orders []ordermodel.Order
	var err error
	count, err = ordermodel.GetInstance().GetDb().Where("uuid = ?", uuid).Limit(int(pageSize), int((page-1)*pageSize)).OrderBy("id desc").FindAndCount(&orders)

	for _, v := range orders {
		var order = ordermodel.OrderDetail{}
		order.Order = v
		for _, item := range goods {
			if item["goods_id"] == v.GoodsId {
				order.GoodsName = item["desc"].(string)
			}
		}
		res = append(res, order)
	}
	fmt.Println(err)
	return
}

func VerifyRecip(uuid string, recipe string) error {
	url_buy := config.GetConf().IosBuyUrl
	//url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
	oriData, _ := base64.StdEncoding.DecodeString(recipe)
	//var reqData, _ = json.Marshal(map[string]interface{}{"receipt-data": oriData,"password":"21dca532bf4e4380a349e51863c23d84"})
	var reqData = "{\"receipt-data\":\"" + string(oriData) + "\",\"password\":" + "\"" + config.GetConf().IosBuySec + "\"}"
	var rs, err = httpclient.FastHttpPost(url_buy, map[string]string{"content-type": "application/json"}, []byte(reqData), 60)
	fmt.Println(string(rs), "****", reqData)
	var res map[string]interface{}
	err = json.Unmarshal([]byte(rs), &res)
	if res["status"].(float64) == 0 {
		var orders = res["receipt"].(map[string]interface{})["in_app"].([]interface{})
		// 对order排序
		sort.Slice(orders, func(i, j int) bool {
			return orders[i].(map[string]interface{})["purchase_date_ms"].(string) > orders[j].(map[string]interface{})["purchase_date_ms"].(string)
		})

		var goodsId = ""
		var transId = ""
		var originId = ""
		if len(orders) > 0 {
			goodsId = orders[0].(map[string]interface{})["product_id"].(string)
			transId = orders[0].(map[string]interface{})["transaction_id"].(string)
			originId = orders[0].(map[string]interface{})["original_transaction_id"].(string)
		}
		count, _ := ordermodel.GetInstance().GetDb().Where("trans_id = ?", transId).Count(ordermodel.Order{})
		if count > 0 {
			return errors.New("查询不到新订单")
		}
		if goodsId == "" {
			return errors.New("票据无效")
		}
		var good map[string]interface{}
		for _, v := range goods {
			if v["goods_id"].(string) == goodsId {
				good = v
			}
		}
		if good == nil {
			return errors.New("票据无效")
		} else {
			var order = ordermodel.Order{}
			order.Uuid = uuid
			order.Recipe = recipe
			order.Expire = int64(good["expire"].(int))*24*60*60 + time.Now().Unix()
			order.GoodsId = goodsId
			order.TransId = transId
			order.OrginId = originId
			order.CreatedAt = time.Now().Unix()
			_, err := ordermodel.GetInstance().GetDb().Insert(order)
			return err
		}
		return err
	} else {
		return errors.New("购买失败")
	}
}
